/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

/**
 *
 * @author phat10130059
 */
//import static enumeration.EnumerateWindows.Kernel32.*;
//import static enumeration.EnumerateWindows.Psapi.*;
//import static enumeration.EnumerateWindows.User32DLL.*;
import clipboard.TextTransfer;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.ptr.PointerByReference;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jni.DDEClientUrlBrowser;
import jni.Kernel32;
import jni.Psapi;
import jni.User32DLL;
import util.StringUtil;

public class EnumerateWindows {

    private static final int MAX_TITLE_LENGTH = 1024;
    private static final String TASKLIST = "tasklist";
    private static final String KILL = "taskkill /F /IM ";
    private static String tmpTile = "";

//    private static TextTransfer textTransfer = new TextTransfer();
//    public static void main(String[] args) throws Exception {
////        getCurrentWindow();
////        getPathProcess("dfx.exe");
//       
//    }

    public static String getPathProcess(String serviceName) throws Exception {

//        List<String> arrayList = new ArrayList<String>();
        String tmp = "";
        Process p = Runtime.getRuntime().exec("wmic process get description,executablepath");
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.toLowerCase().contains(serviceName)) {
                System.out.println(line);
                List<String> arrayList = StringUtil.cutEmptyString(line);
                if (arrayList.size() > 1) {
                    tmp = arrayList.get(1);
                }
                return tmp;
            }
        }

        return tmp;

    }

    public static void getCurrentWindow() {

        final TextTransfer textTransfer = new TextTransfer();

        while (true) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    System.out.println("==================================");

                    if (activeWindowProcess().equals("chrome.exe")) {

                        try {
                            if (!tmpTile.equals(activeWindowTitle())) {

                                System.out.println(activeWindowTitle());

                                copyUrlBrowser();

                                System.out.println("Clipboard contains:" + textTransfer.getClipboardContents());

                                String url = textTransfer.getClipboardContents().toLowerCase();

                                if (!url.equals("")) {
                                    if (!url.contains(".com")) {
                                        closeTabBrowser();
                                        tmpTile = "";
//                                        System.out.println("cho phep");
                                    } else {
                                        tmpTile = activeWindowTitle();
                                    }

                                    textTransfer.setClipboardContents("");
                                } else {
//                                    System.out.println("vao");
                                    if (activeWindowTitle().trim().toLowerCase().contains("tab mới")
                                            || activeWindowTitle().trim().toLowerCase().contains("new tab")) {
                                        System.out.println("Phat");
                                        tmpTile = activeWindowTitle();
                                        textTransfer.setClipboardContents("");
                                    }
                                }



                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else if (activeWindowProcess().toLowerCase().equals("firefox.exe")
                            || activeWindowProcess().toLowerCase().equals("iexplore.exe")) {

                        String pro = activeWindowProcess();
                        String url = DDEClientUrlBrowser.getUrlBrowser(StringUtil.cutExe(pro).get(0));

                        System.out.println(url);

                        if (url.contains("https://") || url.contains("http://")) {
                            if (!url.contains(".com")) {
                                try {
                                    closeTabBrowser();
                                } catch (AWTException ex) {
                                    ex.printStackTrace();
                                }
                            }
                        }
                        tmpTile = "";

                    } else {
                        tmpTile = "";
                    }
                }
            }).start();

            try {
                Thread.currentThread().sleep(2000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }

        }
    }

    public static String activeWindowTitle() {
        char[] buffer = new char[MAX_TITLE_LENGTH * 2];
        User32DLL.GetWindowTextW(User32DLL.GetForegroundWindow(), buffer, MAX_TITLE_LENGTH);
//        System.out.println("Active window title: " + Native.toString(buffer));
        return Native.toString(buffer).trim();
    }

    public static String activeWindowProcess() {
        char[] buffer = new char[MAX_TITLE_LENGTH * 2];
        PointerByReference pointer = new PointerByReference();
        User32DLL.GetWindowThreadProcessId(User32DLL.GetForegroundWindow(), pointer);
        Pointer process = Kernel32.OpenProcess(Kernel32.PROCESS_QUERY_INFORMATION | Kernel32.PROCESS_VM_READ, false, pointer.getValue());
        Psapi.GetModuleBaseNameW(process, null, buffer, MAX_TITLE_LENGTH);
//        System.out.println("Active window process: " + Native.toString(buffer));
        return Native.toString(buffer);
    }

    public static boolean isProcessRunging(String serviceName) throws Exception {

        Process p = Runtime.getRuntime().exec(TASKLIST);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {

//            System.out.println("check tasklist : "+line);
            if (line.toLowerCase().contains(serviceName)) {
                return true;
            }
        }

        return false;

    }

    public static void killProcess(String serviceName) throws Exception {
        //        System.out.println(serviceName);

        Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "taskkill /F /IM " + serviceName + " /T");

    }

    public static void closeTabBrowser() throws AWTException {

        Robot r = new Robot();
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_W);

        r.keyRelease(KeyEvent.VK_W);
        r.keyRelease(KeyEvent.VK_CONTROL);



    }

    public static void copyUrlBrowser() throws AWTException, InterruptedException {
        Robot r = new Robot();
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_L);
        r.keyRelease(KeyEvent.VK_L);
        r.keyRelease(KeyEvent.VK_CONTROL);

        r.delay(500);

        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_C);
        r.keyRelease(KeyEvent.VK_C);
        r.keyRelease(KeyEvent.VK_CONTROL);

        r.delay(1000);

    }

    public static void copy() throws AWTException {
        Robot r = new Robot();
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_C);
        r.keyRelease(KeyEvent.VK_C);
        r.keyRelease(KeyEvent.VK_CONTROL);
    }
}
